package com.yx.changdao.web.config.shiro.realm;

import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.JwtUtils;
import com.yx.changdao.common.entity.SysUser;
import com.yx.changdao.service.SysUserService;
import com.yx.changdao.web.config.shiro.JWTCredentialsMatcher;
import com.yx.changdao.web.config.shiro.token.JwtToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description: <br/>
 * 自定义Realm用于验证token
 * <p>
 * <br/>
 * @Auther: zhangqi
 * @create 2019/11/12 13:27
 */
public class JWTShiroRealm extends AuthorizingRealm {

    @Autowired
    protected SysUserService userService;

    public JWTShiroRealm() {
        // 设置验证方法
        this.setCredentialsMatcher(new JWTCredentialsMatcher());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authcToken;
        String token = jwtToken.getToken();

        SysUser user = null;
        try {
            user = userService.getJwtTokenInfo(JwtUtils.getJwtload(token).getUserID(), token);
        } catch (AlertException e) {
            e.printStackTrace();
        }
        if (user == null) {
//            return null;
            throw new AccountException("token过期，请重新登录");
        }

        SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(user, user.getSalt(), "jwtRealm");

        return authenticationInfo;
    }
}
